import useStore from "@/store";
import {DataContent} from "@/model/chat";

const wsWebSocketUrl: string = "ws://127.0.0.1:9000/ws";

export function useWebSocket(handleMessage: any) {
    const webSocket = new WebSocket(wsWebSocketUrl)
    const {user} = useStore();
    const init = () => {
        webSocket.onopen =  handleOpen;
        webSocket.onclose =  handleClose;
        webSocket.onerror = handleError;
        webSocket.onmessage = handleMessage;
    }

    function handleOpen() {
        // 初始化用户channel映射
        webSocket.send(JSON.stringify({
            action: 1,
            extend: {
                userId: user.id
            }
        } as DataContent));
        console.log("通道开启,用户为",user.nickname);
    }
    function handleClose() {
        console.log("通道关闭")
    }
    function handleError() {
        console.log("通道错误")
    }
    init();
    return webSocket;
}

export default useWebSocket;